<?php

function plotGraph($firstDataArr, $secondDataArr, $firstTypeName, $secondTypeName, $labelsArr, $graphName)
{
	require_once('jpgraph-3.5.0b1/src/jpgraph.php');
	require_once('jpgraph-3.5.0b1/src/jpgraph_line.php');

	$averageDataArr = calcAverage($firstDataArr, $secondDataArr);

	$firstArrMinValue = minValueFromArr($firstDataArr);
	$secondArrMinValue = minValueFromArr($secondDataArr);
	$firstArrMaxValue = maxValueFromArr($firstDataArr);
	$secondArrMaxValue = maxValueFromArr($secondDataArr);
	$minValue = minValue($firstArrMinValue, $secondArrMinValue);
	$maxValue = maxValue($firstArrMaxValue, $secondArrMaxValue);

	// Setup the graph
	$graph = new Graph(count($firstDataArr) * 30, 250);
	$graph->SetScale("textlin");

	$theme_class=new UniversalTheme;

	$graph->SetTheme($theme_class);
	$graph->img->SetAntiAliasing(false);
	$graph->title->Set($graphName);
	$graph->SetBox(false);

	$graph->img->SetAntiAliasing();
    $graph->xaxis->SetPos( 'min' );
	$graph->yaxis->HideZeroLabel();
	$graph->yaxis->HideLine(false);
	$graph->yaxis->HideTicks(false,false);

	$graph->xgrid->Show();
	$graph->xgrid->SetLineStyle("solid");
	$graph->xaxis->SetTickLabels($labelsArr);
	$graph->xgrid->SetColor('#E3E3E3');

	// Create the first line
	$p1 = new LinePlot($firstDataArr);
	$graph->Add($p1);
	$p1->SetColor("#FF0000");
	$p1->SetLegend($firstTypeName);

	// Create the second line
	$p2 = new LinePlot($secondDataArr);
	$graph->Add($p2);
	$p2->SetColor("#00FFFF");
	$p2->SetLegend($secondTypeName);

	// Create the third line
	$p3 = new LinePlot($averageDataArr);
	$graph->Add($p3);
	$p3->SetColor("#00FF40");
	$p3->SetLegend('Average');

	$graph->legend->SetFrameWeight(1);

	// Output line
	$graph->Stroke();
}

function calcAverage($firstDataArr, $secondDataArr)
{
	$averageArr = array();
	for ($i=0; $i < count($firstDataArr) ; $i++) 
	{ 
		$averageArr[$i] = ($firstDataArr[$i] + $secondDataArr[$i]) / 2;
	}

	return $averageArr;
}

function maxValueFromArr($arr)
{
	$maxValue = $arr[0];
	for ($i=1; $i < count($arr) ; $i++) 
	{ 
		if ($maxValue > $arr[$i]) 
		{
			$maxValue = $arr[$i];
		}
	}

	return $maxValue;
}

function minValueFromArr($arr)
{
	$minValue = $arr[0];
	for ($i=1; $i < count($arr) ; $i++) 
	{ 
		if ($minValue < $arr[$i]) 
		{
			$minValue = $arr[$i];
		}
	}

	return $minValue;
}

function minValue($firstValue, $secondValue)
{
	$result = $secondValue;
	if ($firstValue < $result) 
	{
		$result = $firstValue;
	}

	return $result;
}

function maxValue($firstValue, $secondValue)
{
	$result = $secondValue;
	if ($firstValue > $result) 
	{
		$result = $firstValue;
	}

	return $result;
}

?>